package org.x.user.service.impl;


import com.mybatisflex.core.query.QueryWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.x.common.config.BusinessException;
import org.x.user.dto.AssignRolesDTO;
import org.x.user.mapper.SysRoleMapper;
import org.x.user.mapper.SysUserMapper;
import org.x.user.service.ISysRoleUserService;
import org.x.user.entity.SysRoleUserEntity;
import org.x.user.mapper.SysRoleUserMapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;

/**
 * 用户角色关联表 服务层实现。
 *
 * @author mybatis-flex-helper automatic generation
 * @since 1.0
 */
@Service
public class SysRoleUserServiceImpl extends ServiceImpl<SysRoleUserMapper, SysRoleUserEntity> implements ISysRoleUserService {

    @Autowired
    private SysRoleUserMapper sysRoleUserMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Override
    public int assignRoles(AssignRolesDTO assignRolesDTO) {
        // 校验用户存在性
        if (sysUserMapper.selectOneById(assignRolesDTO.getUserId()) == null) {
            throw new BusinessException("用户不存在");
        }

        // 校验角色有效性
        if (assignRolesDTO.getRoleIds() == null || assignRolesDTO.getRoleIds().length == 0) {
            throw new BusinessException("角色列表不能为空");
        }

        for (Long roleId : assignRolesDTO.getRoleIds()) {
            if (sysRoleMapper.selectOneById(roleId) == null) {
                throw new BusinessException("角色不存在，ID: " + roleId);
            }
        }

        // 删除旧的角色分配
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(SysRoleUserEntity::getUserId, assignRolesDTO.getUserId());
        sysRoleUserMapper.deleteByQuery(queryWrapper);

        int count = 0;
        SysRoleUserEntity sysRoleUserEntity = new SysRoleUserEntity();
        sysRoleUserEntity.setUserId(assignRolesDTO.getUserId());

        for (Long roleId : assignRolesDTO.getRoleIds()) {
            sysRoleUserEntity.setRoleId(roleId);
            count += sysRoleUserMapper.insert(sysRoleUserEntity);
        }

        return count;
    }

}